const api = require('../../utils/api')
const config = require('../../utils/config')

Page({
  data: {
    tabs: [
      { id: 'all', name: '全部' },
      { id: 0, name: '待支付' },
      { id: 1, name: '待发货' },
      { id: 2, name: '待收货' },
      { id: 3, name: '已完成' },
      { id: 4, name: '已取消' }
    ],
    activeTab: 'all',
    orderList: [],
    page: 1,
    pageSize: 10,
    loading: false,
    noMoreData: false
  },

  onLoad(options) {
    // 获取传入的订单类型参数
    let type = options.type || 'all';
    
    // 记录原始tab类型
    console.log('传入的订单类型:', type);
    
    this.setData({
      activeTab: type
    });
    
    // 加载订单列表
    this.loadOrderList(true);
  },

  // 切换Tab页签
  switchTab(e) {
    const type = e.currentTarget.dataset.type;
    if (type === this.data.activeTab) return;
    
    this.setData({
      activeTab: type,
      orderList: [],
      page: 1,
      noMoreData: false
    });
    
    this.loadOrderList(true);
  },

  // 加载订单列表
  loadOrderList(refresh = false) {
    if (this.data.loading) return;
    
    const { page, pageSize, activeTab } = this.data;
    
    if (refresh) {
      this.setData({
        page: 1,
        orderList: [],
        noMoreData: false
      });
    }
    
    this.setData({ loading: true });
    
    // 构建查询参数
    const params = {
      page,
      pageSize,
      status: activeTab === 'all' ? '' : activeTab
    };
    
    console.log('获取订单列表参数:', params);
    console.log('请求的API路径:', config.API.ORDER.LIST);
    
    // 调用API获取订单列表
    api.get(config.API.ORDER.LIST, params)
      .then(res => {
        const { list, total } = res.data;
        
        console.log('获取订单列表成功:', res.data);
        
        // 合并订单列表数据
        const orderList = refresh ? list : this.data.orderList.concat(list);
        
        this.setData({
          orderList,
          noMoreData: orderList.length >= total,
          loading: false
        });
        
        wx.stopPullDownRefresh();
      })
      .catch(err => {
        console.error('加载订单列表失败', err);
        // 增加详细错误信息日志
        console.error('错误详情:', JSON.stringify(err));
        console.error('请求状态:', err.statusCode);
        console.error('错误信息:', err.errMsg || err.message);
        
        this.setData({ loading: false });
        wx.stopPullDownRefresh();
        
        wx.showToast({
          title: '加载失败，请重试',
          icon: 'none'
        });
      });
  },

  // 查看订单详情
  viewOrderDetail(e) {
    const orderId = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: `/pages/order/detail/index?id=${orderId}`
    });
  },

  // 取消订单
  cancelOrder(e) {
    const orderId = e.currentTarget.dataset.id;
    
    wx.showModal({
      title: '提示',
      content: '确定要取消该订单吗？',
      success: (res) => {
        if (res.confirm) {
          // 显示加载提示
          wx.showLoading({
            title: '处理中...',
            mask: true
          });
          
          // 调用取消订单API
          const url = config.API.ORDER.CANCEL.replace(':id', orderId);
          api.put(url)
            .then(() => {
              wx.hideLoading();
              
              wx.showToast({
                title: '订单已取消',
                icon: 'success'
              });
              
              // 刷新订单列表
              this.loadOrderList(true);
            })
            .catch(err => {
              wx.hideLoading();
              console.error('取消订单失败', err);
              
              wx.showToast({
                title: '取消失败，请重试',
                icon: 'none'
              });
            });
        }
      }
    });
  },

  // 去支付
  goPay(e) {
    const orderId = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: `/pages/order/payment/index?id=${orderId}`
    });
  },

  // 确认收货
  confirmReceipt(e) {
    const orderId = e.currentTarget.dataset.id;
    
    wx.showModal({
      title: '提示',
      content: '确认已收到商品？',
      success: (res) => {
        if (res.confirm) {
          // 显示加载提示
          wx.showLoading({
            title: '处理中...',
            mask: true
          });
          
          // 调用确认收货API
          const url = config.API.ORDER.RECEIVE.replace(':id', orderId);
          api.put(url)
            .then(() => {
              wx.hideLoading();
              
              wx.showToast({
                title: '确认收货成功',
                icon: 'success'
              });
              
              // 刷新订单列表
              this.loadOrderList(true);
            })
            .catch(err => {
              wx.hideLoading();
              console.error('确认收货失败', err);
              
              wx.showToast({
                title: '操作失败，请重试',
                icon: 'none'
              });
            });
        }
      }
    });
  },

  // 查看物流
  viewLogistics(e) {
    const orderId = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: `/pages/order/logistics/index?id=${orderId}`
    });
  },

  // 下拉刷新
  onPullDownRefresh() {
    this.loadOrderList(true);
  },

  // 上拉加载更多
  onReachBottom() {
    if (this.data.noMoreData || this.data.loading) return;
    
    this.setData({
      page: this.data.page + 1
    });
    
    this.loadOrderList();
  }
}) 